# coding:utf-8
from django.http import HttpResponse
import json
import random
import mock.util as util
import mock.sms as sms
import mock.default as default
from mock.models import API, Router, Response, MockLog
from mock.requestcheck import checkUrl
requestError = """{
    status_code: 1400,
    content: ' request.body不能为空！'
}"""
emptyErrorRequest = '''{
    status_code: 2400,
    err_msg: ' 方法或路由不存在！'
}'''

apiErrorResponse = '''{
    status_code: 2404,
    err_msg: 'Api查询为空！'
}'''
routerErrorResponse = '''{
    status_code: 3404,
    err_msg: 'Router查询为空！'
}'''
responseErrorResponse = '''{
    status_code: 4404,
    err_msg: 'Response查询为空！'
}'''
jsonErrorRequest = '''{
    status_code: 5400,
    err_msg: '请求的json格式错误！'
}'''
APIErrorRequest = '''{
    status_code: 5500,
    err_msg: 'API接口不唯一,或不存在，请确认mock配置是否正确！'
}'''

RouterErrorRequest = '''{
    status_code: 5500,
    err_msg: 'API-Router不唯一,或不存在，请确认mock配置是否正确！'
}'''

# Create your views here.


def createJSONResponse(text):
    a = HttpResponse(
        content=text, content_type="application/json;charset=utf-8")
    return a


def mockindex(request, api=None, router=None):
    """
    mock服务的统一入口，根据API的值确定处理方式
    :param request:
    :param api:
    :param router:
    :return:
    """
    checkurlRes = checkUrl(request, api, router)
    if checkurlRes == True:
        if api == 'sms':
            return sms.sms(request, api, router)
        else:
            res = getResponseData(api, router)
            if res == "APIErrorRequest":
                return  createJSONResponse(APIErrorRequest)
            elif res == "RouterErrorRequest":
                return  createJSONResponse(RouterErrorRequest)
            else:
                return  createJSONResponse(res)            
    elif checkurlRes == 'apiErrorResponse':
        return createJSONResponse(apiErrorResponse)
    elif checkurlRes == 'requestError':
        return createJSONResponse(requestError)
    elif checkurlRes == 'jsonErrorRequest':
        return createJSONResponse(jsonErrorRequest)
    elif checkurlRes == 'emptyErrorRequest':
        return createJSONResponse(emptyErrorRequest)
    elif checkurlRes == 'routerErrorResponse':
        return createJSONResponse(routerErrorResponse)
    elif checkurlRes == 'responseErrorResponse':
        return createJSONResponse(responseErrorResponse)
    else:
        return default.defaultResponse(request, api, router)


def getResponseData(api=None, router=None):
    """
    根据API和router获取response返回的模板
    :param api:
    :param router:
    :return str:
    """
    print("api:",api)
    apiList =list(API.objects.filter(path=api).values())
    if len(apiList) == 1:
        print('apiList0:',apiList[0])
        routerList = Router.objects.filter(api=apiList[0]["id"], path=router).values()
        routerList = list(routerList)
        print('routerList:',routerList[0])
        if len(routerList) == 1:
            responseList = Response.objects.filter(router=routerList[0]['id'], status=True).values()
            responseList = list(responseList)
            print('responseList:',responseList[0])
            response = responseList[0]['json']
            print('response:',response)
            return  response
        else:
            return  'RouterErrorRequest'
    else:
        return  'APIErrorRequest'


def mockLog(api=None, router=None, responseData=None):
    MockLog.objects.create(apipath=api, routerpath=router,
                           json=responseData, status=True)


def index(request):
    return HttpResponse('Hello world')
